﻿using FastEventBus.Attribute;
using FastEventBus.Definition;
using FastEventBus.Entity;
using FastEventBus.Exception;
using FastUtil.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastEventBus.Realization
{
    public class RedisEventStroage : IFastEventStroage
    {
        public Dictionary<string, List<IFastEventHandler>> HandlerDic = new Dictionary<string, List<IFastEventHandler>>();
        public void RegistHandler(IFastEventHandler Handler)
        {
            FastEventChannel Channel = System.Attribute.GetCustomAttribute(Handler.GetType(), typeof(FastEventChannel)) as FastEventChannel;
            if (Channel != null && !string.IsNullOrEmpty(Channel.ChannelName))
            {
                if (!HandlerDic.ContainsKey(Channel.ChannelName))
                {
                    List<IFastEventHandler> HandlerList = new List<IFastEventHandler>();
                    HandlerList.Add(Handler);
                    HandlerDic.Add(Channel.ChannelName, HandlerList);
                }
                else
                {
                    List<IFastEventHandler> HandlerList = HandlerDic[Channel.ChannelName];
                    HandlerList.Add(Handler);
                    HandlerDic[Channel.ChannelName] = HandlerList;
                }
            }
            else
            {
                throw new EventHandlerDefineExcption(string.Format("事件处理类{0}未正确声明Channel", Handler.GetType().FullName));
            }
        }

        public List<IFastEventHandler> ResolveHandler(string ChannelName)
        {
            return HandlerDic[ChannelName];
        }

        public void WriteEvent(FastEventParam Param)
        {
            RedisUtil.SetHash(Param.ChannelName, Param.EventID, JsonConvert.SerializeObject(Param), 15);
        }

        public FastEventParam ReadEvent(string ChannelName, string EventID)
        {
            return JsonConvert.DeserializeObject<FastEventParam>(RedisUtil.GetHash(ChannelName, EventID, 15));
        }

        public void ACKEvent(string ChannelName, string EventID)
        {
            RedisUtil.DelteHash(ChannelName, EventID, 15);
        }


    }
}
